import os.path

import numpy as np
import re

def readzzuNeuralGPS(folder):
    return ReadGPStxt(folder, device_type='zzuNeural').processing()

def read3birdPosAttGPS(folder):
    return ReadGPStxt(folder, device_type='3birdPosAtt').processing()

class ReadGPStxt:
    """
    合并文件夹内gps.txt：1.剔除未定位行；2.剔除储存异常行
    需要指定文件来自哪种设备类型：'zzuNeural', '3birdPosAtt'
    return:
        程序运行结束后，会在这个文件夹下新建一个progressed_data文件夹，其中保存以下文件
        1.合并后的txt,其中仅包含经纬度和时间戳(经纬度已转换为dddd格式)
        2.用于绘制地图路线的txt，其中包含经纬度
    """
    def __init__(self, folder, device_type='zzuNeural'):
        self.folder = folder
        self.device_type = device_type
        self.line_front = None  # 仅用于三足鸟设备的多个gps文件
        self.sametimestamp = None

    def processing(self):
        # 创建用于保存的文件夹
        if not os.path.exists(self.folder+'/progressed_data'):
            os.makedirs(self.folder+'/progressed_data')
        save_path = self.folder+'/progressed_data'
        merger_gps_file = save_path + '/merger_gps.txt'# 建立空的用于合并的txt文档：merger_gps.txt
        open(merger_gps_file, 'a').close()

        mapplot_gps_file = save_path + '/mapplot_gps.txt'  # 建立空的用于绘图的txt文档：mapplot_gps.txt
        open(mapplot_gps_file, 'a').close()

        if self.device_type == '3birdPosAtt':
            gpsfile_list = [file for file in os.listdir(self.folder) if file.startswith('gps_data_')]  # 获取当前文件夹下所有gps_data_开头的文件
            gpsfile_list.sort(key=lambda x: int(x.split('_')[2].split('.')[0]))  # 按照数字大小排序

            # 访问文件夹下的gps.txt，逐行处理
            for txt_name in gpsfile_list:
                print(f'正在合并{txt_name}')
                with open(os.path.join(self.folder, txt_name), 'r', encoding='utf-8') as f:
                    line_end = sum(1 for line in f)
                    f.seek(0)
                    for index, line in enumerate(f):
                        line_list = line.split(',')
                        # print(line_list)
                        if self.line_front != None: # 检查是否存在半行
                            line = self.line_front + line
                            self.line_front = None
                            line_list = line.split(',')
                        if index == line_end-1:
                            self.line_front = line if len(line_list) <= 13 else None
                            continue
                        # if len(line_list) == 14:
                        #     print(f'{txt_name}文件中的第{index+1}行缺少时间戳')
                        #     continue
                        if len(line_list) >= 5 and line_list[3].strip() != '':
                            # if line_list[-1] == self.sametimestamp:  # 是否时间戳重复
                            #     continue
                            E, N, timestamp = line_list[5], line_list[3], line_list[-1][line_list[-1].find('*')+1:line_list[-1].find('\n')] # 去除换行符
                            E, N = ddmm2dddd(E), ddmm2dddd(N)
                            with open(merger_gps_file, 'a') as merge_f:
                                merge_f.write(f'{E},{N},{timestamp}\n')
                            with open(mapplot_gps_file, 'a') as mapplot_f:
                                mapplot_f.write(f'{E},{N}\n')
                            # self.sametimestamp = line_list[-1]


        elif self.device_type == 'zzuNeural':
            txt_name = [file for file in os.listdir(self.folder) if file.startswith('GPS_')][0]  # 获取当前文件夹下所有GPS_开头的文件
            with open(os.path.join(self.folder, txt_name), 'r', encoding='utf-8') as f:
                for index, line in enumerate(f):
                    line_list = line.split(',')
                    # print(line_list)
                    if all(item in line_list for item in ['$GNRMC', 'N', 'E']):
                        if line_list[3].strip() != '' and line_list[5].strip() != '':
                            # if line_list[-2].strip() == '':  # 时间戳缺失？
                            #     continue
                            E, N, timestamp = line_list[5], line_list[3], line_list[-1][line_list[-1].find(' ')+1:line_list[-1].find('\n')]  # 去除换行符
                            E, N = ddmm2dddd(E), ddmm2dddd(N)
                            with open(merger_gps_file, 'a') as merge_f:
                                merge_f.write(f'{E},{N},{timestamp}\n')
                            with open(mapplot_gps_file, 'a') as mapplot_f:
                                mapplot_f.write(f'{E},{N}\n')

                    # print(line_list)
                    # if '$GNRMC' not in line_list:
                    #     continue
                    # if len(line_list) > 6:
                    #
        print(f'GPS.txt文件处理完毕')

def ddmm2dddd(EN):
    return np.floor(float(EN)/100) + (float(EN) % 100)/60

if __name__ == '__main__':
    # folder = 'D:/About_code/FlyNueralProject/original_data/P19/20240507/PM/GPS data'
    # ReadGPStxt(folder, device_type='zzuNeural').processing()

    folder = 'C:/Users/HP/Desktop/3birds/1.ALLTEST/20240907_IntegratedNavigation/device_1'
    ReadGPStxt(folder, device_type='3birdPosAtt').processing()
